package com.xjc.infra.util;


import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

/**
 * Copyright 2012 CHNBS. All right reserved.
 * 
 * @Description 读取spring注入的.properties文件
 * @version
 * @auther pengzhifu
 * @email
 * @CreationDate Feb 22, 2012 2:33:12 PM
 * @ModificationHistory
 * 
 */
public class SystemGlobals extends PropertyPlaceholderConfigurer {
	public SystemGlobals() {// tomcat错误添加一个构造函数

	}
	private static Map<String, String> propertiesMap = new HashMap<String,String>();

	/**
	 * 取得properties中的值
	 * 
	 * @param name
	 * @return
	 */
	public static String getProperty(String name) {
		String value = propertiesMap.get(name);
		if (StringUtils.isBlank(value)) {
			return value;
		}
		String reg = "\\$\\{[A-Za-z0-9_-|.]+}";
		Pattern pattern = Pattern.compile(reg);
		Matcher matcher = pattern.matcher(value);
		String nvalue = value;
		while (matcher.find()) {
			String matchStr = matcher.group(0);
			String matchKey = matchStr.substring(2, matchStr.length() - 1);
			if (!propertiesMap.containsKey(matchKey)) {
				continue;
			}
			String matchValue = getProperty(matchKey);
			nvalue = nvalue.replace(matchStr, matchValue);
		}
		propertiesMap.put(name, nvalue);
		return nvalue;
	}
	/**
	 * 获取属性
	 * @author liangcz
	 * @date   2018年1月2日 下午7:51:14
	 * @return String
	 */
	public static String getProperty(String name,String defaultValue){
		String value = getProperty(name);
		if(StringUtils.isBlank(value)){
			return defaultValue;
		}
		return value;
	}
	/**
	 * 替换properties中变量
	 * 
	 * @param key
	 * @param map
	 * @return
	 */
	public static String getProperty(String key, Map<String, String> map) {
		String rstr = propertiesMap.get(key);
		for (Entry<?, ?> entry : map.entrySet()) {
			rstr = rstr.replace(entry.getKey().toString(), entry.getValue()
					.toString());
		}
		return rstr;
	}

	@Override
	protected void processProperties(
			ConfigurableListableBeanFactory beanFactory, Properties props)
			throws BeansException {

		super.processProperties(beanFactory, props);
		propertiesMap = new HashMap<String, String>();
		String s;
		for (Object key : props.keySet()) {

			String keyStr = key.toString();
			try {
				s = new String(props.getProperty(keyStr).getBytes("UTF-8"),
						"UTF-8");
				propertiesMap.put(keyStr, s);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

		}

	}
}